# -*- coding:utf8 -*-
#
##############################
# Auther : free.won
# Email  : freefis@gmail.com
# Licence on GPL licence
##############################
  
from django.shortcuts import render_to_response
from django.http import HttpResponse , HttpResponseRedirect
from django.contrib.sessions.models import Session
from django.db.models import Q
from django.utils.encoding import force_unicode
from django.core.cache import cache

from django.contrib.auth.models import User
from mysite.daohang.models import Site
from mysite.daohang.crawler import bitren,nfans,kissbit
from utils import zh2py,sql_format

import md5
import os.path
import logging
import string

def main_page(request):
    return render_to_response("main.html")



def share_page(request):
    """ get URL info from User. """
    postParam = request.POST
    if not postParam.has_key("url"):
        return render_to_response("share.html")
    else:
        _url = postParam['url']
        _name = postParam['name']
        _pinyin = zh2py(_name)
        q = Site(name=_name,url=_url,pinyin=_pinyin)
        q.save()
        return render_to_response('debug.html',{'info':"1"})



def index_page(request):
    return render_to_response("index.html")

def search_page(request):
    """
        the core of application.
    """
    postParam = request.POST
    _keyword = postParam['keyword']
    keyword = force_unicode(_keyword)
    
    # from utils.py , translate keywords as a ORM command.
    sql = sql_format(keyword) 
    
    #
    #  get the first part from user as a key to memche.
    #  when he/her go on to input, there will never be the db.operation.
    #  until he reinput new keyword from a blank.
    #
    cache_keyword = _keyword.split(" ")[0]

    if cache.get(cache_keyword):
        cache_QuerySet = cache.get(cache_keyword)
        final_sql = 'QuerySet=cache_QuerySet.filter(' + sql  + ')'
    else:
        cache_QuerySet = Site.objects.filter(Q(name__icontains=cache_keyword) | \
                Q(pinyin__icontains=cache_keyword))
        cache.set(cache_keyword,cache_QuerySet,3*60)
        final_sql = 'QuerySet=Site.objects.filter(' + sql + ')'
    
    exec(final_sql)
    return render_to_response("search.html",{"info":QuerySet})
